package mn.idax.exchange.otc.web;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mn.idax.exchange.auth.bean.AuthInfo;
import mn.idax.exchange.auth.util.AuthInfoUtils;
import mn.idax.exchange.common.bean.ResponseData;
import mn.idax.exchange.otc.constant.ConstantError;
import mn.idax.exchange.otc.constant.RequestUrlConstant;
import mn.idax.exchange.otc.domain.*;
import mn.idax.exchange.otc.entity.OTCSysDictionaryItem;
import mn.idax.exchange.otc.entity.OTCUser;
import mn.idax.exchange.otc.entity.User;
import mn.idax.exchange.otc.enums.UserEnum;
import mn.idax.exchange.otc.enums.response.UserResponseEnum;
import mn.idax.exchange.otc.exception.IdaxException;
import mn.idax.exchange.otc.service.*;
import mn.idax.exchange.otc.util.ParamUtils;
import mn.idax.exchange.otc.util.PicValidateUtil;
import mn.idax.exchange.otc.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

//import mn.idax.exchange.common.PicValidateUtil;

/**
 * Create by jack_huang on 2018/8/9
 * 用户
 */

@Api(value = "用户", tags = {"用户"})
@RestController
@RequestMapping(RequestUrlConstant.MODULE_USER)
public class UserController {

    @Autowired
    private OTCUserService otcUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserLanguageService userLanguageService;
    @Autowired
    private OTCCertificateService otcCertificateService;

    @Autowired
    private FileUrlService fileUrlService;

    @Autowired
    private AliyunOSSService aliyunOSSService;

    @Autowired
    private OTCSysDictionaryItemService otcSysDictionaryItemService;


    @PostMapping(RequestUrlConstant.USER_GOODLISTORBLACKLIST)
    @ApiOperation(value = "信任名单或者黑名单展示", notes = "需传入查询参数（JSON），（jack_huang，自测通过)")
    public ResponseData getGoodList(@RequestBody UserListType userListType) {

        Integer type = userListType.getType();

        Integer pageIndex = userListType.getPageIndex();
        Integer pageSize = userListType.getPageSize();

        if (pageIndex == null || pageIndex < 0) {
            pageIndex = 0;
        }
        //防止用户恶意攻击
        if (pageSize == null || pageSize <= 0 || pageSize > 1000) {
            pageSize = 1000;
        }
        //1 白名单 2 黑名单
        if (type == null) {
            throw new IdaxException(UserResponseEnum.USER_LISTTYPEISNULL.getRespCode());
        }
        if (!type.equals(UserEnum.trust_List.getCode()) && !type.equals(UserEnum.black_List.getCode())) {
            throw new IdaxException(UserResponseEnum.USER_LISTTYPE.getRespCode());
        }
        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        UserPageParamsDTO userPageParamsDTO = new UserPageParamsDTO(userId, type, pageIndex, pageSize);
        UserListResultDTO userListResult = otcUserService.getUserGroupMembers(userPageParamsDTO);
        return ResponseData.success(userListResult);
    }

    @PostMapping(RequestUrlConstant.USER_GOODLISTADD)
    @ApiOperation(value = "加入信任名单", notes = "加入信任名单，（jack_huang，自测通过)")
    public ResponseData addGoodList(@RequestBody CommentUserIdDTO commentUserIdDTO) {

        String uniqueKey = commentUserIdDTO.getUniqueKey();
        if (StringUtils.isEmpty(uniqueKey)) {
            throw new IdaxException(UserResponseEnum.UNIQUEKEYISEMPTY.getRespCode());
        }

        OTCUser otcUser = otcUserService.getOtcUserByUniqueKey(uniqueKey);
        if (otcUser == null) {
            throw new IdaxException(UserResponseEnum.USER_ADDGOODLISTFAIL.getRespCode());
        }

        Integer beControlUserId = otcUser.getUserid();

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        if (!otcUserService.addGoodList(beControlUserId, userId)) {
            throw new IdaxException(UserResponseEnum.USER_ADDGOODLISTFAIL.getRespCode());
        }
        return ResponseData.success();
    }

    @PostMapping(RequestUrlConstant.USER_GOODLISTREMOVE)
    @ApiOperation(value = "移除信任名单", notes = "移除信任名单，（jack_huang，自测通过)")
    public ResponseData removeGoodList(@RequestBody CommentUserIdDTO commentUserIdDTO) {

        String uniqueKey = commentUserIdDTO.getUniqueKey();
        if (StringUtils.isEmpty(uniqueKey)) {
            throw new IdaxException(UserResponseEnum.UNIQUEKEYISEMPTY.getRespCode());
        }

        OTCUser otcUser = otcUserService.getOtcUserByUniqueKey(uniqueKey);
        if (otcUser == null) {
            throw new IdaxException(UserResponseEnum.USER_ADDGOODLISTFAIL.getRespCode());
        }
        Integer beControlUserId = otcUser.getUserid();

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        if (!otcUserService.removeTrustOrBlack(beControlUserId, userId)) {
            throw new IdaxException(UserResponseEnum.USER_REMOVEGOODLISTFAIL.getRespCode());
        }
        return ResponseData.success();
    }


    @PostMapping(RequestUrlConstant.USER_BLACKLISTADD)
    @ApiOperation(value = "加入黑名单", notes = "加入黑名单，（jack_huang，自测通过)")
    public ResponseData addBlackList(@RequestBody CommentUserIdDTO commentUserIdDTO) {

        String uniqueKey = commentUserIdDTO.getUniqueKey();
        if (StringUtils.isEmpty(uniqueKey)) {
            throw new IdaxException(UserResponseEnum.UNIQUEKEYISEMPTY.getRespCode());
        }

        OTCUser otcUser = otcUserService.getOtcUserByUniqueKey(uniqueKey);
        if (otcUser == null) {
            throw new IdaxException(UserResponseEnum.USER_ADDGOODLISTFAIL.getRespCode());
        }
        Integer beControlUserId = otcUser.getUserid();
        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        if (!otcUserService.addBlackList(beControlUserId, userId)) {
            throw new IdaxException(UserResponseEnum.USER_ADDBLACKLISTFAIL.getRespCode());
        }
        return ResponseData.success();
    }

    @PostMapping(RequestUrlConstant.USER_BLACKLISTREMOVE)
    @ApiOperation(value = "移除黑名单", notes = "移除黑名单，（jack_huang，自测通过)")
    public ResponseData removeBlackList(@RequestBody CommentUserIdDTO commentUserIdDTO) {

        String uniqueKey = commentUserIdDTO.getUniqueKey();
        if (StringUtils.isEmpty(uniqueKey)) {
            throw new IdaxException(UserResponseEnum.UNIQUEKEYISEMPTY.getRespCode());
        }

        OTCUser otcUser = otcUserService.getOtcUserByUniqueKey(uniqueKey);
        if (otcUser == null) {
            throw new IdaxException(UserResponseEnum.USER_ADDGOODLISTFAIL.getRespCode());
        }
        Integer beControlUserId = otcUser.getUserid();

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        if (!otcUserService.removeTrustOrBlack(beControlUserId, userId)) {
            throw new IdaxException(UserResponseEnum.USER_REMOVEBLOCKLISTFAIL.getRespCode());
        }
        return ResponseData.success();
    }

    @PostMapping(RequestUrlConstant.USER_COLLECTIONUSERS)
    @ApiOperation(value = "当前用户收录的信任名单数和黑名单数", notes = "当前用户收录的信任名单数和黑名单数，（jack_huang，自测通过)")
    public ResponseData getUserCollectionUsers() {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        UserCollectionUsersDTO userCollectionUsersDTO = otcUserService.getUserCollectionUsers(userId);
        return ResponseData.success(userCollectionUsersDTO);
    }

    /**
     * 功能描述:
     * 验证昵称是否可修改
     *
     * @param:
     * @return:
     * @auther: dison
     * @date: 2018/8/24 15:14
     */
    @PostMapping(RequestUrlConstant.VERIFY_USABLE_UPDATE_NICKNAME)
    @ApiOperation(value = "验证昵称是否可修改", notes = "验证昵称是否可修改（沈迪雄，自测通过)")
    public ResponseData verifyUsableUpdateNickName() {
        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        String nickName = this.userService.verifyUsableUpdateNickName(userId);
        OTCUser otcUser = this.otcUserService.getOTCUserByUserId(userId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("nickName", StringUtils.isEmpty(nickName) ? "" : nickName);
//        jsonObject.put("icon",StringUtils.isEmpty(otcUser.getIconurl()) ? "" : otcUser.getIconurl());
        jsonObject.put("icon", fileUrlService.dealFileUrlAddress(otcUser.getIconurl()));
        return ResponseData.success(jsonObject);
    }


    /**
     * 功能描述:
     * 修改用户昵称
     *
     * @param:
     * @return:
     * @auther: dison
     * @date: 2018/8/24 15:22
     */
    @PostMapping(RequestUrlConstant.USER_UPDATE_NICK_NAME)
    @ApiOperation(value = "修改用户昵称", notes = "修改用户昵称（沈迪雄，自测通过)")
    public ResponseData updateNickName(@RequestBody UserUpdateNickNameDTO userUpdateNickNameDTO) {
        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        if (!userService.updateOTCNickName(userId, userUpdateNickNameDTO.getNickName())) {
            throw new IdaxException(UserResponseEnum.USER_UPDATE_NICK_NAME_FAIL.getRespCode());
        }
        return ResponseData.success();
    }

    /**
     * 功能描述:
     * 修改用户头像
     *
     * @param:
     * @return:
     * @auther: dison
     * @date: 2018/8/24 15:23
     */
    @PostMapping(RequestUrlConstant.USER_UPDATE_ICON)
    @ApiOperation(value = "修改用户头像", notes = "修改用户头像（沈迪雄，自测通过)")
    public ResponseData updateIcon(@RequestBody UserUpdateIconDTO userUpdateIconDTO) {
        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        boolean updateIconFlag = this.otcUserService.updateIcon(userId, userUpdateIconDTO.getIcon());
        if (!updateIconFlag) {
            throw new IdaxException(UserResponseEnum.USER_UPDATE_ICON_FAIL.getRespCode());
        }
        return ResponseData.success();
    }


    @PostMapping(RequestUrlConstant.UserGoodNumAndBadNum)
    @ApiOperation(value = "当前用户收到的好评数和差评数", notes = "当前用户收到的好评数和差评数,(jack_huang，自测通过)")
    public ResponseData getUserGoodNumAndBadNum() {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        UserGoodNumAndBadNum userGoodNumAndBadNum = otcUserService.getUserGoodNumAndBadNum(userId);
        return ResponseData.success(userGoodNumAndBadNum);
    }


    @PostMapping(RequestUrlConstant.SAVE_USER_LANGUAGE)
    @ApiOperation(value = "更新用户当前的语言", notes = "更新用户当前的语言,(jack_huang，自测通过)")
    public ResponseData saveUserLanguage(@RequestBody UserLanguageRequest userLanguageRequest, HttpServletRequest httpServletRequest) {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        userLanguageRequest.setUserid(userId);
        userLanguageRequest.setUsersource(ParamUtils.getRequestSourceCode(httpServletRequest));

        String language = ParamUtils.getLanguageByRequest(httpServletRequest);
        if (StringUtils.isEmpty(language)) {
            throw new IdaxException(UserResponseEnum.USER_LANGUAGE_IS_EMPTY.getRespCode());
        } else {
            userLanguageRequest.setLanguage(language.replace("-", "_"));
        }

        if (userLanguageService.queryLanguage(userLanguageRequest) == null) {
            userLanguageService.insertLanguage(userLanguageRequest);
        } else {
            userLanguageService.updateLanguage(userLanguageRequest);
        }

        return ResponseData.success();
    }

    @PostMapping(RequestUrlConstant.APPLY_USER_CERTIFICATE)
    @ApiOperation(value = "申请用户资质", notes = "申请用户资质")
    public ResponseData applyUserCertificate(@RequestBody UserApplyCertificateRequest userApplyCertificateRequest) {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        //实名认证
        User user = userService.getUserById(userId);
        if (!user.getIscertificate()){
            throw new IdaxException(ConstantError.NOT_CERTIFICATE_CODE);
        }

        userApplyCertificateRequest.setUserId(userId);

        return otcCertificateService.applyUserCertificate(userApplyCertificateRequest);
    }

    @PostMapping(RequestUrlConstant.GET_USER_CERTIFICATE)
    @ApiOperation(value = "获取用户资质", notes = "获取用户资质")
    public ResponseData getUserCertificate(@RequestBody GetUserCertificateRequest getUserCertificateRequest) {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        getUserCertificateRequest.setUserId(userId);

        return ResponseData.success(otcCertificateService.getUserCertificate(getUserCertificateRequest));
    }


    @PostMapping(RequestUrlConstant.GET_MY_EXAMINE_LIST)
    @ApiOperation(value = "获取我的审核列表", notes = "获取我的审核列表")
    public ResponseData getMyExamineList(@RequestBody PageRequestDTO pageRequestDTO) {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        return ResponseData.success(otcCertificateService.myExamineList(userId,pageRequestDTO));
    }

    @PostMapping(RequestUrlConstant.GET_CERTIFICATE_DETAILS)
    @ApiOperation(value = "获取资质详情", notes = "获取资质详情")
    public ResponseData getCertificateDetails(@RequestBody GetCertificateDetailsRequest getCertificateDetailsRequest) {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        getCertificateDetailsRequest.setUserId(userId);
        return ResponseData.success(otcCertificateService.getCertificateDetails(getCertificateDetailsRequest));
    }

    @PostMapping(RequestUrlConstant.CERTIFICATE_EXAMINE)
    @ApiOperation(value = "资质审核", notes = "资质审核")
    public ResponseData certificateExamine(@RequestBody CertificateExamineRequest certificateExamineRequest) {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        certificateExamineRequest.setUserId(userId);
        return otcCertificateService.certificateExamine(certificateExamineRequest);
    }


    @PostMapping(RequestUrlConstant.GET_SYSTEM)
    @ApiOperation(value = "获取系统配置", notes = "获取系统配置")
    public ResponseData getSystem(@RequestBody GetSysyemRequest getSysyemRequest) {

        if (getSysyemRequest == null || getSysyemRequest.getItemValue() < 1) {
            return ResponseData.success();
        }
        OTCSysDictionaryItem otcSysDictionaryItem1 = otcSysDictionaryItemService.getItemByDictIdAndItemValue(10, getSysyemRequest.getItemValue());
        Map resultMap = new HashMap<>();
        resultMap.put("itemDesc", otcSysDictionaryItem1.getItemdesc());
        return ResponseData.success(resultMap);
    }

    @ApiOperation("上传资质图片")
    @RequestMapping(value = RequestUrlConstant.IMG_UPLOAD, consumes = "multipart/*", headers = "content-type=multipart/form-data", method = RequestMethod.POST)
    public ResponseData imgUpload( MultipartHttpServletRequest request) throws IOException {
        MultipartFile multipartFile;
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
        }

        Map<String, MultipartFile> fileMap = request.getFileMap();
        for (Map.Entry<String, MultipartFile> set : fileMap.entrySet()) {
            multipartFile = set.getValue();
            if (multipartFile != null) {

                if (multipartFile.getSize() > 2097152) {
                    return ResponseData.error(ConstantError.UPLOAD_FILE_EXCEED_CODE, ConstantError.UPLOAD_FILE_EXCEED_MSG);
                }

                String filename = multipartFile.getOriginalFilename();
                String fileNameSuffix = filename.substring(filename.lastIndexOf("."));
                if (!org.apache.commons.lang3.StringUtils.equalsIgnoreCase(".JPG", fileNameSuffix) && !org.apache.commons.lang3.StringUtils.equalsIgnoreCase(".JPEG", fileNameSuffix) && !org.apache.commons.lang3.StringUtils.equalsIgnoreCase(".PNG", fileNameSuffix)) {
                    return ResponseData.error(ConstantError.PICTURE_FORMAT_CODE, ConstantError.PICTURE_FORMAT_MSG);
                }
                String picType = "";
                try {
                    picType = PicValidateUtil.getPicType(multipartFile.getInputStream());
                } catch (IOException e) {
                }
                if (!org.apache.commons.lang3.StringUtils.equalsIgnoreCase(".JPG", picType) && !org.apache.commons.lang3.StringUtils.equalsIgnoreCase(".JPEG", picType) && !org.apache.commons.lang3.StringUtils.equalsIgnoreCase(".PNG", picType)) {
                    return ResponseData.error(ConstantError.PICTURE_FORMAT_CODE, ConstantError.PICTURE_FORMAT_MSG);
                }
                /***
                 * 上传
                 */
                String imgUrl = aliyunOSSService.uploadStream(multipartFile.getInputStream(), filename);
                return ResponseData.success(imgUrl);
            } else {
                return ResponseData.error(ConstantError.MISSING_PICTURE_DATA_CODE, ConstantError.MISSING_PICTURE_DATA_MSG);
            }
        }
        return ResponseData.error(ConstantError.MISSING_PICTURE_DATA_CODE, ConstantError.MISSING_PICTURE_DATA_MSG);
    }


}
